package cvi.com.reader.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cvi.com.reader.R;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.adapter.PersonalCollectAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.CollcetDisplayDataListener;
import cvi.com.reader.bean.DeleteAllCollcetDataListener;
import cvi.com.reader.bean.DraftsBean;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/30.
 * 草稿箱
 */

public class PersonalCollectFragment extends BaseFragment implements PersonalCollectAdapter.DeleteListener, DeleteAllCollcetDataListener {

    @BindView(R.id.gridview)
    MyGridView gridview;
    /* @BindView(R.id.delete_all)
     LinearLayout deleteAll;*/
    Unbinder unbinder;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private String type;
    private List<DraftsBean.DataBean> dataBeanList = new ArrayList<>();
    private List<ChartDataBean.DataBean> chartDataBeanList = new ArrayList<>();
    private PersonalCollectAdapter personalCollectAdapter = null;
    public DialogPlus deleteDialog;
    private CollcetDisplayDataListener collcetDisplayDataListener;

    public CollcetDisplayDataListener getCollcetDisplayDataListener() {
        return collcetDisplayDataListener;
    }

    public void setCollcetDisplayDataListener(CollcetDisplayDataListener collcetDisplayDataListener) {
        this.collcetDisplayDataListener = collcetDisplayDataListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        type = bundle.getString("type");
        unbinder = ButterKnife.bind(this, super.onCreateView(inflater, container, savedInstanceState));
        initSmartRefreshLayout();
        Log.d("PersonalCollectFragment", "type333=" + type);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragemt_personal;

    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                initData();
            }
        });

    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void initData() {
        getMyCollectData();

    }

    //我的收藏数据
    private void getMyCollectData() {
        NetWorkManager.getInstance().getNetWorkApiService().getCollectData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        getData(response, "3");
                        smartRefreshLayout.finishRefresh(true);
                    }
                });
    }


    private void getData(JSONObject response, String type) {
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            DraftsBean.DataBean rowsBean = (DraftsBean.DataBean) JSONObject.toJavaObject(object, DraftsBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            dataBeanList.add(rowsBean);
        }
        if (0 == dataBeanList.size()) {
            noData.setVisibility(View.VISIBLE);
            Log.d("sddddd", "我的收藏1111");
            smartRefreshLayout.setEnableRefresh(false);
            collcetDisplayDataListener.onCollcetDisplay("0");
        } else {
            for (int i = 0; i < dataBeanList.size(); i++) {
                DraftsBean.DataBean dataBean = dataBeanList.get(i);
                ChartDataBean.DataBean chartBean = new ChartDataBean.DataBean();
                if (Hawk.contains("LoginBean")) {
                    LoginBean loginBean = Hawk.get("LoginBean");
                    ChartDataBean.DataBean.UserBean userBean = new ChartDataBean.DataBean.UserBean();
                    userBean.setAvatar(loginBean.getData().getUser_info().getAvatar());
                    userBean.setRealname(loginBean.getData().getUser_info().getName());
                    // userBean.setId(loginBean.getMsg().getId());
                    chartBean.setUser(userBean);
                }
                chartBean.setId(dataBean.getId());
                ChartDataBean.DataBean.MaterialBean materialBean = new ChartDataBean.DataBean.MaterialBean();
                materialBean.setId(dataBean.getId());
                materialBean.setAuthor(dataBean.getAuthor());
                materialBean.setMaterial_name(dataBean.getMaterial_name());
                materialBean.setContent(dataBean.getContent());
                materialBean.setMedia_path(dataBean.getMedia_path());
                materialBean.setType(dataBean.getType());
                materialBean.setStatus(dataBean.getStatus());
                materialBean.setBg_img(dataBean.getBg_img());
                materialBean.setCover_img(dataBean.getCover_img());
                chartBean.setMaterial(materialBean);
                chartDataBeanList.add(chartBean);
            }
            smartRefreshLayout.setEnableRefresh(true);
            noData.setVisibility(View.GONE);
            collcetDisplayDataListener.onCollcetDisplay("1");
        }
        personalCollectAdapter = new PersonalCollectAdapter(getActivity(), dataBeanList, chartDataBeanList);
        gridview.setAdapter(personalCollectAdapter);
        personalCollectAdapter.setDeleteListener(this);
        personalCollectAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initView() {
        stateView.getBackground().setAlpha(153);
    }

    @Override
    public void onDeleteClick(int id) {
        showDialog("0", id);

    }

    private void deleteCollect(int id) {
        NetWorkManager.getInstance().getNetWorkApiService().deleteCollcetData(id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        dataBeanList.clear();
                        getMyCollectData();
                        Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_LONG).show();
                    }
                });

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        PersonalActivity personalActivity = (PersonalActivity) activity;
        personalActivity.setDeleteAllCollcetDataListener(this);
        collcetDisplayDataListener = (CollcetDisplayDataListener) getActivity();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void deleteAllData() {
        NetWorkManager.getInstance().getNetWorkApiService().deleteAllCollcetData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        dataBeanList.clear();
                        getMyCollectData();
                        Toast.makeText(getActivity(), "删除全部成功！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void showDialog(String flag, int id) {
        {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_delete, null);
            Button confirm = view.findViewById(R.id.confir_btn);
            Button cancel = view.findViewById(R.id.cancel_btn);
            TextView tv = view.findViewById(R.id.tips);
            if ("1".equals(flag)) {
                tv.setText("确定要全部删除吗？");
            } else {
                tv.setText("确定要删除吗？");
            }
            deleteDialog = DialogPlus.newDialog(getActivity())
                    .setContentHolder(new ViewHolder(view))
                    .setCancelable(true)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(new OnDismissListener() {
                        @Override
                        public void onDismiss(DialogPlus dialog) {

                        }
                    }).create();
            deleteDialog.show();
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if ("1".equals(flag)) {
                        deleteAllData();
                    } else {
                        deleteCollect(id);
                    }
                    deleteDialog.dismiss();
                    Intent intent = new Intent(constant.TAB_MYRECEIVER);
                    getActivity().sendBroadcast(intent);      //发送广播
                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    deleteDialog.dismiss();
                }
            });
        }
    }

    @Override
    public void onDEleteAll(String flag) {
        showDialog("1", -1);
    }
}
